﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Text;
using System.IO;
using System.Xml;

namespace MediaPortal.GUI.iPlayer
{
    static class Favorites
    {
        /// <summary>
        /// Save the favorites
        /// </summary>
        public static void SaveFavoritesXML(string section, List<Serie> series)
        {
            string dir = MediaPortal.Configuration.Config.GetFolder(MediaPortal.Configuration.Config.Dir.Config);
            string filename = dir + @"\iplayer_fav.xml";


            XmlDocument document = new XmlDocument();
            XmlElement root = null;

            if (File.Exists(filename)) {
                document.Load(filename);
                root = document.DocumentElement;
            }
            
            if (root == null)
            {
            root = document.CreateElement("profile");
            document.AppendChild(root);
            }

            XmlNode sectionNode = root.SelectSingleNode(GetSectionsPath(section));
            if(sectionNode != null) sectionNode.ParentNode.RemoveChild(sectionNode);

            int i = 0;
            foreach (Serie serie in series)
            {
                Favorites.SetValue(document, section, "programName." + i.ToString(), serie.title);
                Favorites.SetValue(document, section, "programUrl" + i.ToString(), serie.url);
                if(serie.host != null)
                    Favorites.SetValue(document, section, "programHost" + i.ToString(), serie.host);
                i++;
            }

            using (StreamWriter stream = new StreamWriter(filename, false))
            {
                document.Save(stream);
                stream.Flush();
                stream.Close();
            }
        }

        /// <summary>
        /// Load the favorites
        /// </summary>
        public static List<Serie> LoadFavoritesXML(string section)
        {
            List<Serie> series = new List<Serie>();

            // Load
            string dir = MediaPortal.Configuration.Config.GetFolder(MediaPortal.Configuration.Config.Dir.Config);
            using (MediaPortal.Profile.Settings reader = new MediaPortal.Profile.Settings(dir + @"\iplayer_fav.xml", false))
            {
                int i = 0;
                bool allFound = false;
                while (!allFound)
                {
                    string result = reader.GetValueAsString(section, "programName." + i.ToString(), "");
                    if (result.Equals(""))
                        allFound = true;
                    else
                    {
                        series.Add(
                            new Serie(
                                StringUtils.MakeFirstUpper(result),
                                reader.GetValueAsString(section, "programUrl" + i.ToString(),""),
                                reader.GetValue(section, "programHost" + i.ToString())
                                )
                            );
                        i++;
                    }
                }
            }

            return series;
        }

        public static void SetValue(XmlDocument document, string section, string entry, object value)
        {
            string valueString = value.ToString();

            if (document.DocumentElement == null)
            {
                XmlElement node = document.CreateElement("profile");
                document.AppendChild(node);
            }
            XmlElement root = document.DocumentElement;
            // Get the section element and add it if it's not there
            XmlNode sectionNode = root.SelectSingleNode(GetSectionsPath(section));
            if (sectionNode == null)
            {
                XmlElement element = document.CreateElement("section");
                XmlAttribute attribute = document.CreateAttribute("name");
                attribute.Value = section;
                element.Attributes.Append(attribute);
                sectionNode = root.AppendChild(element);
            }

            // Get the entry element and add it if it's not there
            XmlNode entryNode = sectionNode.SelectSingleNode(GetEntryPath(entry));
            if (entryNode == null)
            {
                XmlElement element = document.CreateElement("entry");
                XmlAttribute attribute = document.CreateAttribute("name");
                attribute.Value = entry;
                element.Attributes.Append(attribute);
                entryNode = sectionNode.AppendChild(element);
            }
            entryNode.InnerText = valueString;
        }

        private static string GetSectionsPath(string section)
        {
            return "section[@name=\"" + section + "\"]";
        }
        private static string GetEntryPath(string entry)
        {
            return "entry[@name=\"" + entry + "\"]";
        }

    }
}
